package com.cvai.filter;

import com.alibaba.fastjson.JSON;
import com.cvai.R.Result;
import com.cvai.context.BaseContext;
import com.cvai.domain.po.User;
import com.cvai.properties.JwtProperties;
import com.cvai.properties.LLMproperties;
import com.cvai.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

@WebFilter("/*")
@Component // 确保Spring能识别并管理这个Bean
@Slf4j
public class CvFilter implements Filter {
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 设置CORS响应头
        configureCorsHeaders(response);

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            // 对于OPTIONS请求，直接返回200状态码
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        if(request.getRequestURI().contains("login")||request.getRequestURI().contains("register")||request.getRequestURI().contains("memory")
        || request.getRequestURI().contains("render") || request.getRequestURI().contains("callback") || request.getRequestURI().contains("code")){
            log.info("访问放行为：{}", request.getRequestURI());
            filterChain.doFilter(request, response);
            return;
        }
        // 执行业务逻辑
        try {
            handleBusinessLogic(request, response, filterChain);
        } catch (Exception e) {
            log.error("Error handling business logic", e);
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            Result<String> result = Result.error("token验证失败,请登录");
            response.getWriter().write(JSON.toJSONString(result));
        }
    }

    private void configureCorsHeaders(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*"); // 允许特定源访问
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Max-Age", "3600"); // 预检请求的有效期
        response.setHeader("Access-Control-Allow-Credentials", "true"); // 允许凭证
    }

    private void handleBusinessLogic(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 在这里处理你的业务逻辑
        String token = request.getHeader(jwtProperties.getTokenName());
        if (token == null) {
            if (request.getMethod().equalsIgnoreCase("POST") && request.getRequestURI().contains("chat")) {
                String memoryId = request.getRequestURI().split("/", 3)[2];
                if (redisTemplate.opsForValue().get(memoryId) == null) {
                    filterChain.doFilter(request, response);
                    return;
                } else {
                    response.setStatus(401);
                    response.setContentType("application/json;charset=UTF-8");

                    Result<String> result = Result.error("token验证失败,请登录");
                    response.getWriter().write(JSON.toJSONString(result));
                    return;
                }
            }
        }

        try {
            log.info("当前用户token为：{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecret(), token);
            User user = JSON.parseObject(claims.get(jwtProperties.getTokenName()).toString(), User.class);
            if(redisTemplate.opsForValue().get(token+"_"+user.getId().toString())==null)
                throw new RuntimeException("token验证失败,请登录");
            BaseContext.setCurrentUser(user);
            log.info("当前用户为：{}", user);
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            Result<String> result = Result.error("token验证失败,请登录");
            response.getWriter().write(JSON.toJSONString(result));
        }
    }

    @Override
    public void destroy() {
        // 销毁操作
    }
}